
const template = require('./template')

class MyPlugin {
  constructor (options) {
    this.options = options
  }
  apply (compiler) {
    compiler.hooks.compilation.tap('MyPlugin', (compilation) => {
      // console.log(Object.keys(compilation.hooks).filter(item => /htmlWebpackPlugin/.test(item)))
      if (compilation.hooks.htmlWebpackPluginBeforeHtmlGeneration) {
        compilation.hooks.htmlWebpackPluginBeforeHtmlGeneration.tapAsync('MyPlugin', (data, cb) => {
          if (this.options.jsExternals && Array.isArray(this.options.jsExternals)) {
            data.assets.js = this.options.jsExternals.concat(data.assets.js)
          }
          if (this.options.cssExternals && Array.isArray(this.options.cssExternals)) {
            data.assets.css = this.options.cssExternals.concat(data.assets.css)
          }
          // Tell webpack to move on
          if (this.options.extract) {
            this.extracFile(
              compilation,
              {
                js: data.assets.js,
                css: data.assets.css
              }
            )
          }
          cb(null, data)
        })
      }
    })
  }
  extracFile (compilation, { js, css }) {
    const html = template(JSON.stringify(js), JSON.stringify(css))
    compilation.assets['filelist.js'] = {
      source: () => html,
      size: () => html.size
    }
  }
}

module.exports = MyPlugin
